package com.smart.campus.web.controller.wx;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smart.campus.school.wx.cp.config.WxCpConfiguration;
import com.smart.campus.school.wx.cp.config.WxCpTpConfiguration;
import com.smart.campus.school.wx.cp.utils.JsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpTpService;
import me.chanjar.weixin.cp.api.impl.WxCpTpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpTpPermanentCodeInfo;
import me.chanjar.weixin.cp.bean.WxCpTpPreauthCode;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Controller
@RequestMapping(value = "/wx")
public class SuiteController {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @PostMapping(produces = "application/xml; charset=UTF-8")
  public String post(@PathVariable Integer agentId,
                     @RequestBody String requestBody,
                     @RequestParam("msg_signature") String signature,
                     @RequestParam("timestamp") String timestamp,
                     @RequestParam("nonce") String nonce) {
    this.logger.info("\n接收微信请求：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
        signature, timestamp, nonce, requestBody);
      agentId = 1000001;
    final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
    WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(requestBody, wxCpService.getWxCpConfigStorage(),
        timestamp, nonce, signature);
    this.logger.debug("\n消息解密后内容为：\n{} ", JsonUtils.toJson(inMessage));
    WxCpXmlOutMessage outMessage = this.route(agentId, inMessage);
    if (outMessage == null) {
      return "";
    }

    String out = outMessage.toEncryptedXml(wxCpService.getWxCpConfigStorage());
    this.logger.debug("\n组装回复信息：{}", out);
    return out;
  }

  private WxCpXmlOutMessage route(Integer agentId, WxCpXmlMessage message) {
    try {
      return WxCpConfiguration.getRouters().get(agentId).route(message);
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    return null;
  }


    @GetMapping(value="/suite/receive/getAuthUrlHtml")
    public String getAuthUrlHtml(Model model, String redirectUri,
                                 String state, HttpServletResponse response) {
        try {
            String agentId = "wwd196420da947673b";
            WxCpTpService wxCpTpService = WxCpTpConfiguration.getCpTpService(agentId);
            String authUrl = wxCpTpService.getPreAuthUrl(redirectUri,state);

           /* String url = "https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info";

            //WxCpTpPreauthCode preauthCode = WxCpTpPreauthCode.fromJson(wxCpTpService.get("https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code",null));

            String params = "{\"pre_auth_code\":\""+ wxCpTpService.getp +"\",\"session_info\":{\"appid\":[],\"auth_type\":1}}";

            String result = wxCpTpService.post(url,params);*/

            model.addAttribute("authUrl",authUrl);
            return "wx/auth";

        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping(value="/doneAuth")
    @ResponseBody
    public String doneAuth(String auth_code) {
        WxCpTpService wxCpTpService = WxCpTpConfiguration.getCpTpService("wwd196420da947673b");
        WxCpTpPermanentCodeInfo wxCpTpPermanentCodeInfo = null;
        try {
            wxCpTpPermanentCodeInfo = wxCpTpService.getPermanentCodeInfo(auth_code);

            String deptUrl = "https://qyapi.weixin.qq.com/cgi-bin/school/department/list?access_token=" + wxCpTpPermanentCodeInfo.getAccessToken();
            String deptList = wxCpTpService.get(deptUrl, null);
            String url = "https://qyapi.weixin.qq.com/cgi-bin/school/user/create_student?access_token=" + wxCpTpPermanentCodeInfo.getAccessToken();

            String result = wxCpTpService.post(url, createUser());
            int a = 1;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        this.logger.debug("\n授权企业信息：\n{} ", JsonUtils.toJson(wxCpTpPermanentCodeInfo));
        return "success";
    }

    @GetMapping(value="/createUser")
    @ResponseBody
    public String createUser(){
        JSONObject jsonObject = null;
        try {
            WxCpTpService wxCpTpService = WxCpTpConfiguration.getCpTpService("wwd196420da947673b");
            String userId = RandomUtils.nextInt()+"";
            String name = "测试"+userId;
            jsonObject = new JSONObject();
            jsonObject.put("student_userid",userId);
            jsonObject.put("name",name);
            Integer[] department = {24};

            jsonObject.put("department",department);
            String url = "https://qyapi.weixin.qq.com/cgi-bin/school/user/create_student?access_token=" + "sx6kfOvNgDG6QXrPbsdxE6skdMQtG5kBLoQsjwgsMahLnTZ6cr3vofTS6sEftt0bzLXDzoRc8rF5qGEioZIdT-uxMOuJhvpQ2V0zSZTcx_24l_qWXw-CctQv4ApEcGJavbCwL5ZqmimOqMvJr3MztcS_la0MCKvGCyofIZizXM0GAN-Us2Ews3aiQwDHgxUqvFZlh5033GbyBLRHJ6jflQ";

            String result = wxCpTpService.post(url, JSON.toJSONString(jsonObject));
            return result;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "success";
    }

    @GetMapping(value="addStudent")
    @ResponseBody
    public String addStudent(){
        String access_token = "_cDg6K9saIMaMeIdlUFZRa4jAA9D3B6FKCzFH2MvJaM";
        WxCpTpService wxCpTpService = WxCpTpConfiguration.getCpTpService("wwd196420da947673b");

        String deptUrl = "https://qyapi.weixin.qq.com/cgi-bin/school/department/list?access_token="+access_token;
        try {
            String deptList =   wxCpTpService.get(deptUrl,null);
            int a = 1;
            return deptList;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping(value="/index")
    public String index(Model model) {
        try {

            model.addAttribute("authUrl","https://www.baidu.com");
            return "wx/index";

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
